package ua.org.nuos.sdms.clientgui.client.view.tabs;

import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
import ua.org.nuos.sdms.clientgui.client.components.builders.UserInfoBuilder;
import ua.org.nuos.sdms.clientgui.client.components.tabs.DataTab;
import ua.org.nuos.sdms.clientgui.client.events.EntityChangedEvent;
import ua.org.nuos.sdms.clientgui.client.listeners.EntityChangedListener;
import ua.org.nuos.sdms.clientgui.server.AppProxy;
import ua.org.nuos.sdms.middle.entity.Group;
import ua.org.nuos.sdms.middle.entity.User;

import java.util.LinkedList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: dio
 * Date: 08.04.12
 * Time: 21:28
 * To change this template use File | Settings | File Templates.
 */
public class GroupMembersTab extends DataTab implements EntityChangedListener<Group> {

    public static final String ID = "GroupMembersTab";
    public static final String CONTENT_WIDTH = "550";
    private static final String caption = "Учасники группы";

    private List<User> members;
    private VerticalLayout content;

    public GroupMembersTab() {
        super(caption);
        init();
    }

    private void init() {
        AppProxy.getInstance().getComponentLocator().addTab(ID, this);
        AppProxy.getInstance().getModelLocator().getGroupContainer().addListener(this);

        content = new VerticalLayout();
        content.setWidth(CONTENT_WIDTH);
        content.setSpacing(true);
        setDataContainer(content);

        changed(null);
    }

    @Override
    public void changed(EntityChangedEvent<Group> groupEntityChangedEvent) {
        if (members == null) {
            members = new LinkedList<User>();
        }
        members.clear();
        Group group = AppProxy.getInstance().getModelLocator().getGroup();
        if (group != null) {
            List<User> l = AppProxy.getInstance().getServiceLocator().getClientBean().findGroupUsers(group.getId());
            if (l != null) {
                members.addAll(l);
            }
        }
        members.remove(AppProxy.getInstance().getServiceLocator().getAuthenticationBean().getCurrentUser());
        refresh();
    }

    private void refresh() {
        content.removeAllComponents();
        content.addComponent(new Label("<h2>Учасники групы:</h2>", Label.CONTENT_XHTML));
        boolean isLeader = isCurrentUserLeaderInCurrentGroup();
        for (User user : members) {
            content.addComponent(UserInfoBuilder.build(user, isLeader));
        }
    }

    private boolean isCurrentUserLeaderInCurrentGroup() {
        Group group = AppProxy.getInstance().getModelLocator().getGroup();
        boolean isLeader = false;
        if (group != null) {
            UserInGroup.Type type = AppProxy.getInstance().getServiceLocator().getClientBean()
                    .findCurrentUserInGroupStatus(group.getId());
            isLeader = UserInGroup.Type.LEADER.equals(type);
        }
        return isLeader;
    }
}
